package com.wzh.websocket.config;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import java.security.Principal;
import java.util.Map;

/**
 * @Author zh wang
 * @Create 2025/5/16 19:55
 */
public class UserHandshakeInterceptor extends DefaultHandshakeHandler {

    @Override
    protected Principal determineUser(
            ServerHttpRequest request,
            WebSocketHandler wsHandler,
            Map<String, Object> attributes
    ) {
        // 从URL参数中获取userId（对应前端连接时传递的 ?userId=xxx）
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
        String userId = servletRequest.getServletRequest().getParameter("userId");
        System.out.println("UserHandshakeInterceptor.determineUser: " + userId);
        return () -> userId; // 将用户ID绑定到STOMP会话
    }
}
